﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using H2.Streams;
using System.IO;
using System.Windows.Forms;

namespace Mystery
{
    public class SBSP
    {
        public class CollisionBSP
        {
            public const int Offset = 36;

            public class Vertex
            {
                public const int Offset = 56;
                public const int Size = 16;

                public float X;
                public float Y;
                public float Z;
                public short FirstEdge;
            }

            public Vertex[] Vertices;
        }

        private BoundingBox Bounds;
        public CollisionBSP CollisionModel;

        public bool Contains(float x, float y, float z)
        {
            return Bounds.Contains(x, y, z);
        }

        public void ReadFrom(MapStream map, int magic)
        {
            int startOffset = (int)map.Position;

            CollisionModel = new CollisionBSP();
            map.ReadReflexiveAt(startOffset + CollisionBSP.Offset, magic);

            int collisionSBSPStartOffset = (int)map.Position;

            Bounds = new BoundingBox();
            CollisionModel.Vertices = new CollisionBSP.Vertex[map.ReadReflexiveAt(collisionSBSPStartOffset + CollisionBSP.Vertex.Offset, magic)];
            int verticesStartOffset = (int)map.Position;
            for (int i = 0; i < CollisionModel.Vertices.Length; ++i)
            {
                map.Position = verticesStartOffset + (i * CollisionBSP.Vertex.Size);

                CollisionBSP.Vertex v = new CollisionBSP.Vertex();
                CollisionModel.Vertices[i] = v;

                v.X = map.ReadFloat();
                v.Y = map.ReadFloat();
                v.Z = map.ReadFloat();
                v.FirstEdge = map.ReadInt16();

                Bounds.Add(v.X, v.Y, v.Z);
            }
        }
    }
}
